//
//  Userinfo.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/6/19.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import TZImagePickerController

class Userinfo: HMViewController{
     // MARK: - 变量
    var signUpPhone: String? // 上个界面传的手机号
    var question: String?    // 上个界面传的问题
    var answerValue: String? // 上个界面传的答案
    var portraitUrl: String? // 保存头像路径
    // 遮罩view
    var _maskView: UIView?
    // MARK: - 常量
    let nameButton = UIButton()
    let headPortrait = UIImageView()

    let nickname = UILabel()
    let sex   = UILabel()
    let birth = UILabel()
    let region = UILabel()
    let authentication = UILabel()
    
    let nickField = UITextField()
    let sexSegmented  = UISegmentedControl()
    let birthField = UITextField()
    let regionButtom = UIButton()
    let authenticationSwitch = UISwitch()
    
    let complete = UIButton()
    
    // MARK: - 周期
    override func viewDidLoad() {
        super.viewDidLoad()
        keyBordNotification(this: self, aShow: #selector(keyBoardWillShow(_:)), aHide: #selector(keyBoardWillHide(_:)))
    }
    deinit {
        //移除通知
        NotificationCenter.default.removeObserver(self)
    }
    // MARK: - 配置view
    override func setupView() {
        self.title = "信息"
        view.backgroundColor = UIColor.white
         _maskView = UIView.createMaskView(this: self, action: #selector(onMark))
        
        
        view.addSubview(headPortrait)
        view.addSubview(nameButton)
        
        view.addSubview(nickname)
        view.addSubview(nickField)
        
        view.addSubview(sex)
        view.addSubview(sexSegmented)
        
        view.addSubview(birth)
        view.addSubview(birthField)
        
        view.addSubview(region)
        view.addSubview(regionButtom)
        
        view.addSubview(authentication)
        view.addSubview(authenticationSwitch)
        view.addSubview(complete)
       
        
        headPortrait.topAlign(view: view)
        headPortrait.centerXAlign(view: view)
        headPortrait.widthConstrain(predicate: "100")
        headPortrait.heightConstrain(predicate: "100")
        headPortrait.layer.cornerRadius = 10
        headPortrait.addTapGesture(target: self, action: #selector(changePortrait))
        headPortrait.img(url: "logo.png")
        
        nameButton.topVertically(view: headPortrait, predicate: "10")
        nameButton.centerXAlign(view: view)
//        nameButton.width(view: headPortrait)
        nameButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        nameButton.heightConstrain(predicate: "44")
        nameButton.setTitleColor(UIColor.red, for: .normal)
        nameButton.addTarget(self, action: #selector(changePortrait(sender:)), for: .touchUpInside)
        nameButton.setTitle("点击更换头像", for: .normal)
        
        nickname.topVertically(view: nameButton, predicate: "40")
        nickname.centerXAlign(view: view, predicate: "-100")
        nickname.heightConstrain(predicate: "44")
        nickname.font = UIFont.systemFont(ofSize: 15)
        nickname.text = "昵称："
        
    
        nickField.centerYAlign(view: nickname, predicate: "0")
        nickField.leadingHorizontally(view: nickname, predicate: "10")
        nickField.heightConstrain(predicate: "44")
        nickField.widthConstrain(predicate: "180")
        nickField.placeholder = "不少于2个字符长度"
        nickField.textAlignment = NSTextAlignment.center
        nickField.setValue(UIFont.systemFont(ofSize: 15), forKeyPath: "_placeholderLabel.font")
        nickField.setValue(UIColor.gray, forKeyPath: "_placeholderLabel.textColor")
        let layer = CALayer()
        layer.frame = CGRect.init(x: 0, y: 44, width: 180, height: 2)
        layer.backgroundColor = UIColor.gray.cgColor
        nickField.layer.addSublayer(layer)
        

        sex.topVertically(view: nickname, predicate: "30")
        sex.leadingAlign(view: nickname, predicate: "0")
        sex.height(view: nickname)
        sex.font = nickname.font
        sex.text = "性别："

        
        sexSegmented.centerYAlign(view: sex, predicate: "0")
        sexSegmented.leadingHorizontally(view: sex, predicate: "10")
        sexSegmented.heightConstrain(predicate: "33")
        sexSegmented.insertSegment(with: UIImage.init(named: "nan"), at: 0, animated: true)
        sexSegmented.setWidth(90, forSegmentAt: 0)
        sexSegmented.insertSegment(with: UIImage.init(named: "nv"), at: 1, animated: true)
        sexSegmented.setWidth(90, forSegmentAt: 1)
        sexSegmented.selectedSegmentIndex = 0
        
//        let imgView = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
//        imgView.backgroundColor = UIColor.red
//        sexSegmented.item .addSubview(imgView)
        sexSegmented.addTarget(self, action: #selector(segmentDidChange), for: UIControlEvents.valueChanged)
        
        
        birth.topVertically(view: sex, predicate: "30")
        birth.leadingAlign(view: nickname, predicate: "0")
        birth.height(view: nickname)
        birth.font = nickname.font
        birth.text = "出生："
        
        
        birthField.leadingHorizontally(view: birth, predicate: "10")
        birthField.centerYAlign(view: birth, predicate: "0")
        birthField.height(view: nickField)
        birthField.width(view: nickField)
        birthField.placeholder = "请输入出生年"
        birthField.setValue(UIFont.systemFont(ofSize: 15), forKeyPath: "_placeholderLabel.font")
        birthField.setValue(UIColor.gray, forKeyPath: "_placeholderLabel.textColor")
//        birthField.contentVerticalAlignment = UIControlContentVerticalAlignment.center;
        birthField.textAlignment = NSTextAlignment.center   //UITextAlignmentLeft;
        let birthlayer = CALayer()
        birthlayer.frame = CGRect.init(x: 0, y: 44, width: 180, height: 2)
        birthlayer.backgroundColor = UIColor.gray.cgColor
        birthField.layer.addSublayer(birthlayer)
        
        
        region.topVertically(view: birth, predicate: "30")
        region.leadingAlign(view: nickname, predicate: "0")
        region.height(view: nickname)
        region.font = nickname.font
        region.text = "地区："
        
        
        regionButtom.leadingHorizontally(view: region, predicate: "10")
        regionButtom.centerYAlign(view: region, predicate: "0")
        regionButtom.height(view: nickname)
        regionButtom.width(view: nickField)
        regionButtom.setTitle("点击选择地区", for: .normal)
        regionButtom.setTitleColor(UIColor.gray, for: .normal)
        regionButtom.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        let regionlayer = CALayer()
        regionlayer.frame = CGRect.init(x: 0, y: 44, width: 180, height: 2)
        regionlayer.backgroundColor = UIColor.gray.cgColor
        regionButtom.addTarget(self, action: #selector(regionClick), for: UIControlEvents.touchUpInside)
        regionButtom.layer.addSublayer(regionlayer)
        
        
        authentication.topVertically(view: region, predicate: "30")
        authentication.leadingAlign(view: nickname, predicate: "0")
        authentication.height(view: nickname)
        authentication.font = nickname.font
        authentication.text = "认证医生："
        
        authenticationSwitch.leadingHorizontally(view: regionButtom, predicate: "-50")
        authenticationSwitch.centerYAlign(view: authentication, predicate: "0")
        authenticationSwitch.setOn(false, animated: true)
//        authenticationSwitch.thumbTintColor = UIColor.red
        authenticationSwitch.addTarget(self, action: #selector(switchChanged), for: UIControlEvents.valueChanged)
        
        
        complete.topVertically(view: authentication, predicate: "30")
        complete.leadingAlign(view: view, predicate: "60")
        complete.trailingAlign(view: view, predicate: "-60")
        complete.backgroundColor =   UIColor.RGBA(r: 180, g: 180, b: 180, a: 1)
        complete.isEnabled = false
        complete.heightConstrain(predicate: "44")
        complete.setTitle("完成注册", for: .normal)
        complete.setTitleColor(UIColor.white, for: .normal)
        complete.addTarget(self, action: #selector(completeClick), for: .touchUpInside)
        complete.layer.cornerRadius = 20
    }
    
    @objc func segmentDidChange(segmented: UISegmentedControl) {
        //获得选项的索引
//        print(segmented.selectedSegmentIndex)
        //获得选择的文字
//        print(segmented.titleForSegment(at: segmented.selectedSegmentIndex)!)
    }
    
    @objc func changePortrait(sender: UIButton) {
        
        HMPhoto.shareInstance.pushTZImagePickerController(self, max: 1, column: 1, isSelectOriginal: false)   //
        HMPhoto.shareInstance.hmImagePickerVc!.didFinishPickingPhotosHandle = {
                (photos, assets, isSelectOriginalPhoto) -> () in
            
            
            self.headPortrait.image = photos![0]
            //回调
            
            let _date = Date()
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let dateString = formatter.string(from: _date)
            
            
            let datas  = NSMutableArray()
            let imgsStr = NSMutableArray()
            var i = 0
            //        for photo in photos {
            //            print("----->", photo)
            let zipImageData: Data = UIImageJPEGRepresentation(photos![0], 0.2)!
            let str = "\(dateString)-\(0)"
            imgsStr.add(str)
            datas.add(zipImageData)
            //            i += 1
            //        }
            
            
            NetRequestTool.shareInstance.met = .post
            NetRequestTool.upload(url: "/user/image/upload", data:datas as! [Data] ,imgName:imgsStr as! [String] ,parameters: [:], success: { (json) in
                self.portraitUrl = json["url"].stringValue
            }) { (err, msg) in
                RKDropdownAlert.title("温馨提示！", message: "获取图片路径失败")
            }
//            print("----->>",photos)
        }
    }
    
    @objc func regionClick(sender: UIButton) {
        print("点地区")
    }
    
    /**
     * 开启医生认证
     */
    @objc func switchChanged(sender: UISwitch) {
        if(sender.isOn == true) {
           UserDefaults.standard.set(2, forKey: "hm_role")
           self.complete.setTitle("下一步", for: .normal)
        }else {
           UserDefaults.standard.set(1, forKey: "hm_role")
           self.complete.setTitle("完成注册", for: .normal)
        }
    }
    
    /**
     *
     */
    @objc func completeClick(sender: UIButton) {
        requiredData()
    }
    
    /**
     * 普通-注册请求
     */
    private func requiredData() {
        HMUtils.share.showHUD(self)
        
        let phoneStr = self.signUpPhone!
        let nickName = self.nickField.text!
        let birth = self.birthField.text!
        let sex =  sexSegmented.selectedSegmentIndex == 0 ? 1 : 2 // 1男 2女
        let region = "广东" //(self.regionButtom.titleLabel?.text)!
        let isDoctor = self.authenticationSwitch.isOn  //== true ? "true" : "false"
        let iconUrl: String = ((portraitUrl?.count)! > 0) ? portraitUrl! :  ""
        let platform = configure.shareConfigure.hm_platform
        let securityAnswer = ["question1": self.question, "answer1": self.answerValue]  // 密保问题
        let dic: [String: Any] = ["phone":phoneStr,"nickname": nickName,"birth":birth,"region":region,"isDoctor": isDoctor, "iconUrl": iconUrl, "sex":sex,"platform": platform, "securityAnswer": securityAnswer]
        
    
        
        NetRequestTool.shareInstance.met = .post
        NetRequestTool.shareInstance.Content_Type = "application/json;charset=UTF-8"
        NetRequestTool.shareInstance.encoding = "init"  //= JSONEncoding.default
        NetRequestTool.shareInstance.newFun = true
        NetRequestTool.requestForJSON(url: "user/register", parameters: dic, success: { (json) in
//            print("-------->>", json)
            HMUtils.share.hideHUD()
            if (self.authenticationSwitch.isOn == true){
                 let _authentication = Authentication()
                self.pushViewController(_authentication, animated: true)
            }else {
                self.navigationController?.popToRootViewController(animated: true)
            }
            
            
        }, fail: { (err, msg) in
            HMUtils.share.hideHUD()
            RKDropdownAlert.title("温馨提醒!", message: msg)
        }) {
            
        }
    }
    
    
    // UITapGestureRecognizer
    @objc func onMark(send: UITapGestureRecognizer) {
        _maskView?.removeFromSuperview()
        self.birthField.resignFirstResponder()//结束编辑状态
        self.nickField.resignFirstResponder()//结束编辑状态
    }
    
    /// NSDictionary -> String
    func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData!
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
        
    }
    
    // 设置按钮表现效果
    func setButtonSytle()  {
        //判断是否开启按钮
            if ( self.nickField.text!.count > 0 && self.birthField.text!.count > 0) {
                openButtonRecognition(setStyleBtn: self.complete, isOpen: true)
            }else {
                openButtonRecognition(setStyleBtn: self.complete, isOpen: false)
            }
    }
    /**
     键盘监控
     */
    @objc func keyBoardWillShow(_ notification: Notification){
        self.view.window?.addSubview(_maskView!)
        print("------->>keyBoardWillShow")
    }
    
    @objc func keyBoardWillHide(_ notification: Notification){
        print("------->>keyBoardWillHide")
        self.setButtonSytle()
    }
    
    // 点键盘按钮
//    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
//        if textField.tag == 102 {
////            self.smsField.becomeFirstResponder()
//        }else {
//
//        }
//        return true
//    }
    
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let text = textField.text!
        let len = text.count + string.count - range.length
        if textField.tag == 101 {
            return (len <= 6)
        }else {
            return (len <= 11)
        }
        
    }
    
}

//extension Userinfo: HMPhotoDelegate {
//
//
//    func photoImagesAndAssets(photos: [UIImage]!, assets: [Any]!, isSelectOriginalPhoto: Bool) {
//
//    }
//}
